package com.wxgo.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;

public class ClassUtils {
	public static String classRootPath = null;

	public static List<Class<?>> scanPackage(String packageName) throws ClassNotFoundException {
		List<Class<?>> classList = new ArrayList<Class<?>>();
		String path = getClassRootPath() + "/" + packageName.replace(".", "/");
		List<String> fileNameList = getAllFileName(path);
		for (String fileName : fileNameList) {
			classList.add(Class.forName(fileName));
		}
		return classList;
	}

	public static List<String> getAllFileName(String path) {
		List<String> fileNameList = new ArrayList<String>();
		File rootFile = new File(path);
		if (rootFile.isFile()) {
			String fileName = rootFile.getPath().replace(PathKit.getRootClassPath(), "").replace(File.separator, ".")
					.replaceFirst(".", "");
			String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
			if (prefix.equals("class")) {
				fileNameList.add(fileName.substring(0, fileName.lastIndexOf(".")));
			}
		} else {
			File[] files = rootFile.listFiles();
			if (files != null) {
				for (File file : files) {
					fileNameList.addAll(getAllFileName(file.getPath()));
				}
			}
		}
		return fileNameList;
	}

	public static String getClassRootPath() {
		if (StrKit.isBlank(classRootPath))
			classRootPath = PathKit.getRootClassPath();
		return classRootPath;
	}

	public static void setClassRootPath(String classRootPath) {
		ClassUtils.classRootPath = classRootPath;
	}
}
